﻿using System;
using Microsoft.Extensions.DependencyInjection;

namespace di会传染
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ServiceCollection services = new ServiceCollection();
            services.AddScoped<Controller>();
            services.AddScoped<ILog, LogTmepl>();
            services.AddScoped<IStorage, StorageTempl>();
            services.AddScoped<IConfig, ConfigTempl>();

            using (var sp = services.BuildServiceProvider())
            {
                var c = sp.GetRequiredService<Controller>();
                c.Test();
            }
        }
    }
    class Controller
    {
        private readonly ILog _log;
        private readonly IStorage _storage;
        public Controller(ILog log, IStorage storage)
        {
            this._log = log;
            this._storage = storage;
        }

        public void Test()
        {
            _log.Log("开始上传");
            _storage.Save("1111", "111.txt");
            _log.Log("上传完毕");
        }
    }

    interface ILog
    {
        public void Log(string msg);
    }
    class LogTmepl : ILog
    {
        void ILog.Log(string msg)
        {
            Console.WriteLine($"日志：{msg}");
        }
    }
    interface IConfig
    {
        public string GetVal(string name);
    }
    class ConfigTempl : IConfig
    {
        public string GetVal(string name)
        {
            return name;
        }
    }
    interface IStorage
    {
        public void Save(string content,string name);
    }
    class StorageTempl : IStorage
    {
        private readonly IConfig iconfig;
        public StorageTempl(IConfig iconfig) {
            this.iconfig = iconfig;
        }
        public void Save(string content, string name)
        {
            string server = iconfig.GetVal("server");
            Console.WriteLine($"向服务器{server}的文件名{name}上传");
        }

    }
}
